using System;
using System.Xml;
using MSScriptControl;
using InfoJetSoft.Service.Entity;
using InfoJetSoft.Service.ManagedCode;
using InfoJetSoft.Service.Util;

namespace InfoJetSoft.Service.Worker
{
	/// <summary>
	/// Summary description for ScriptCodeOnClickWorker.
	/// </summary>
	class ScriptCodeOnClickWorker
	{
		
		public static void OnClick(Form form, string buttonId, string buttonSource)
		{
			ScriptSource scriptSource = form.Manifest.ScriptSource;
			if( scriptSource == null )
			{
				return;
			}

			XmlNode xmlSourceNode = DOMUtil.findNodeByJetId( form, buttonSource );
			
			Microsoft.Office.Interop.InfoPath.SemiTrust.DOMNode sourceNode = null;
			if( xmlSourceNode != null )
			{
				sourceNode = XMLNode.createXMLNode( form, xmlSourceNode, form.XmlNsResolver );
				//CID 0210 //2009.01.20 //Begin
				form.SelectNode = xmlSourceNode;
				//CID 0210 //2009.01.20 //End
			}
			else
			{
				sourceNode = XMLNode.createXMLNode( form, form.XmlDoc.DocumentElement, form.XmlNsResolver );
				//CID 0210 //2009.01.20 //Begin
				form.SelectNode = form.XmlDoc.DocumentElement;
				//CID 0210 //2009.01.20 //End
			}

			try
			{
				if( form.ScriptControlContext == null )
				{
					ScriptControlContext.buildContext( scriptSource, form );
				}

				XDocument xdoc = form.ScriptControlContext.XDocument;
				Application app = form.ScriptControlContext.Application;

				DocActionEvent actionEvent = new DocActionEvent( xdoc, sourceNode );

				ScriptControl scriptControl = form.ScriptControlContext.ScriptControl;

				string onClickName = buttonId + "_OnClick";

				foreach( Procedure proc in scriptControl.Procedures )
				{
					if( proc.Name.Equals( onClickName ) )
					{
						//CID 0474 //2009.12.23 //Begin
						form.Logger.LogUpdate(null);
						//CID 0474 //2009.12.23 //End
						object[] param = new object[]{ actionEvent };
						scriptControl.Run( onClickName, ref param );
						//CID 0474 //2009.12.23 //Begin
						break;
						//CID 0474 //2009.12.23 //End
					}
				}
			}
			catch( Exception e )
			{
                FormUtil.addInnerExceptionMassage(form, buttonId + "_OnClick", e);
			}
		}

	}
}
